#!/usr/bin/env bash

# Copyright Materialize, Inc. All rights reserved.
#
# Use of this software is governed by the Business Source License
# included in the LICENSE file at the root of this repository.
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software will be governed
# by the Apache License, Version 2.0.

set -euo pipefail

mzconduct() {
    bin/ci-builder run stable bin/mzconduct "$@"
}

test_name="$BUILDKITE_PLUGIN_MZCONDUCT_TEST"
workflow="$BUILDKITE_PLUGIN_MZCONDUCT_WORKFLOW"
compose_file="$(bin/ci-builder run stable bin/mzconduct show dir "$test_name")/mzcompose.yml"

mzcompose() {
    bin/ci-builder run stable bin/mzcompose --mz-quiet -f "$compose_file" "$@"
}

# Sometimes build cancellations prevent us from properly cleaning up the last
# Docker Compose run, which can leave old containers or volumes around that will
# interfere with this build.
echo "--- :docker: Purging containers and volumes from previous builds"
mzconduct down --volumes "$test_name"

echo "--- :docker: Rebuilding non-mzbuild containers"
mzconduct build "$test_name"

echo "+++ :docker: mzconduct run $test_name --workflow $workflow" >&2

if ! mzconduct run "$test_name" --workflow "$workflow" ; then
    echo "Command failed! Uploading logs for debugging." >&2
    mzcompose logs --no-color > services.log
    buildkite-agent artifact upload services.log
    exit 1
fi
